/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package telex;

import edu.berkeley.nlp.lm.StupidBackoffLm;
import edu.berkeley.nlp.lm.WordIndexer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Diogo
 */
public class BerkeleyLm {
    StupidBackoffLm <String> lm;
    int mMaxArity;

    public BerkeleyLm(String lmModelPath, int aMaxArity){
        try {
            lm = (StupidBackoffLm<String>) new ObjectInputStream(new FileInputStream(new File(lmModelPath))).readObject();
            mMaxArity = aMaxArity;
        } catch (Exception ex) {
            System.out.println("Erro ao ler o Modelo de Linguagem dos ngramas");
            System.out.println(ex);
        }
    }

    public Query executeQuery(Query aQ){
        int n = aQ.getArity();
        if(aQ.getArity() > mMaxArity){
            System.out.println("Tamanho do n-grama superior ao tamanho máximo");
            return null;
        }

        List<String> ngram = Arrays.asList(aQ.getQueryString().get());
        int[] array = WordIndexer.StaticMethods.toArray(lm.getWordIndexer(), ngram);
        long count = lm.getRawCount(array, 0, ngram.size());

        if(count == -1){
            count = 0;
        }

        aQ.finish(count);

        return aQ;
    }

    public static void main(String[] args) throws FileNotFoundException, IOException{
        BufferedReader br = new BufferedReader(new FileReader (new File ("C:/Users/Diogo/Desktop/ngrams teste berkeley lm/4gms/4gm-0000")));
        PrintStream bw = new PrintStream(new FileOutputStream(new File("C:/Users/Diogo/Desktop/ngrams teste berkeley lm/4gms/4gm-0000-new")));
        int count = 0, count_new = 0;
        String line = "";
        while((line = br.readLine()) != null){
            if(count >= 501){
                bw.println(line);
            }
            count++;
        }
        System.out.println(count_new);
    }

}
